//
//  PPCameraCaptureViewController.m
//  pickpic
//
//  Created by Jinxiao on 10/7/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPCameraCaptureViewController.h"
#import "PPCameraCaptureConfirmViewController.h"
#import "PPCameraViewController.h"
#import "PPCameraAssetsPickerViewController.h"
#import "PPCameraCropViewController.h"

#import <FastttCamera/FastttCamera.h>

@interface PPCameraCaptureViewController () <FastttCameraDelegate, PPAssetsPickerViewControllerDelegate, TOCropViewControllerDelegate>
@property (nonatomic, strong) FastttCamera *camera;
@property (readwrite, nonatomic, strong) UIButton *albumButton;
@property (readwrite, nonatomic, strong) UIButton *cancelButton;
@property (readwrite, nonatomic, strong) UIButton *flashButton;
@property (readwrite, nonatomic, strong) UIButton *toggleButton;
@property (readwrite, nonatomic, strong) UIButton *captureButton;

@property (readwrite, nonatomic, strong) UIButton *fullButton;
@property (readwrite, nonatomic, strong) UIButton *halfButton;
@end

@implementation PPCameraCaptureViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blackColor];

    _camera = [[FastttCamera alloc] init];
    _camera.delegate = self;
    _camera.maxScaledDimension = 10;

    [self fastttAddChildViewController:_camera];

    _albumButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _albumButton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    _albumButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_albumButton setTitle:@"本地相册" forState:UIControlStateNormal];
    [_albumButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_albumButton addTarget:self action:@selector(albumButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_albumButton];

    _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _cancelButton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    [_cancelButton setImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [_cancelButton addTarget:self action:@selector(cancelButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cancelButton];

    _flashButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _flashButton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    _flashButton.adjustsImageWhenHighlighted = NO;
    [_flashButton setImage:[UIImage imageNamed:@"light-off"] forState:UIControlStateNormal];
    [_flashButton setImage:[UIImage imageNamed:@"shan"] forState:UIControlStateHighlighted|UIControlStateSelected];
    [_flashButton setImage:[UIImage imageNamed:@"shan"] forState:UIControlStateSelected];
    [_flashButton addTarget:self action:@selector(flashButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_flashButton];

    _toggleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _toggleButton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    _toggleButton.adjustsImageWhenHighlighted = NO;
    [_toggleButton setImage:[UIImage imageNamed:@"photo"] forState:UIControlStateNormal];
    [_toggleButton setImage:[UIImage imageNamed:@"photo"] forState:UIControlStateHighlighted|UIControlStateSelected];
    [_toggleButton setImage:[UIImage imageNamed:@"photo"] forState:UIControlStateSelected];
    [_toggleButton addTarget:self action:@selector(toggleButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_toggleButton];

    _captureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _captureButton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    [_captureButton setImage:[UIImage imageNamed:@"photo_button"] forState:UIControlStateNormal];
    [_captureButton setImage:[UIImage imageNamed:@"photo_button"] forState:UIControlStateHighlighted];
    [_captureButton addTarget:self action:@selector(captureButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_captureButton];


    _fullButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _fullButton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    _fullButton.adjustsImageWhenHighlighted = NO;
    _fullButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_fullButton setTitle:@"全屏" forState:UIControlStateNormal];
    [_fullButton setTitleColor:[UIColor colorWithRGBHex:0xffffff] forState:UIControlStateNormal];
    [_fullButton setTitleColor:[UIColor colorWithRGBHex:0xffdd17] forState:UIControlStateHighlighted|UIControlStateSelected];
    [_fullButton setTitleColor:[UIColor colorWithRGBHex:0xffdd17] forState:UIControlStateSelected];
    [_fullButton addTarget:self action:@selector(fullButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_fullButton];

    _halfButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _halfButton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    _halfButton.adjustsImageWhenHighlighted = NO;
    _halfButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_halfButton setTitle:@"正方形" forState:UIControlStateNormal];
    [_halfButton setTitleColor:[UIColor colorWithRGBHex:0xffffff] forState:UIControlStateNormal];
    [_halfButton setTitleColor:[UIColor colorWithRGBHex:0xffdd17] forState:UIControlStateHighlighted|UIControlStateSelected];
    [_halfButton setTitleColor:[UIColor colorWithRGBHex:0xffdd17] forState:UIControlStateSelected];
    [_halfButton addTarget:self action:@selector(halfButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_halfButton];

    UIView *anchorView = [[UIView alloc] init];
    anchorView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:anchorView];

    _fullButton.selected = YES;
    _halfButton.selected = NO;

    [_flashButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(_toggleButton.mas_leading).offset(-5);
        make.centerY.equalTo(_cancelButton);
    }];

    [_toggleButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.view).offset(-5);
        make.centerY.equalTo(_cancelButton);
    }];

    [_albumButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(14);
        make.bottom.equalTo(self.view).offset(-30);
    }];

    [_cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(5);
        make.top.equalTo(self.view).offset(21);
    }];

    [_captureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(_albumButton);
    }];

    [anchorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.height.equalTo(@(1));
        make.centerX.equalTo(self.view);
        make.leading.equalTo(_fullButton.mas_leading);
        make.trailing.equalTo(_halfButton.mas_trailing);
    }];

    [_fullButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_captureButton.mas_top).offset(-30);
        make.trailing.equalTo(_halfButton.mas_leading).offset(-30);
    }];

    [_halfButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_fullButton);
    }];

    [self layoutCameraFrameAnimated:NO];
}

- (void)layoutCameraFrameAnimated:(BOOL)animated {

    [_camera.view mas_remakeConstraints:^(MASConstraintMaker *make) {

        if(_fullButton.selected) {
            make.edges.equalTo(self.view);
        } else {
            make.width.equalTo(self.view);
            make.height.equalTo(self.view.mas_width);
            make.centerX.equalTo(self.view);
            make.bottom.equalTo(_fullButton.mas_top).offset(-30);
        }
    }];

    if(animated) {
        [self.view updateConstraintsIfNeeded];

        [UIView animateWithDuration:0.25 delay:0 options:(4 << 16)|UIViewAnimationOptionBeginFromCurrentState animations:^{
            [self.view layoutIfNeeded];
        } completion:nil];
    }

}

- (void)albumButtonDidPressed {
    [MobClick event:@"26"];
    PPCameraAssetsPickerViewController *assetsViewController = [[PPCameraAssetsPickerViewController alloc] init];
    assetsViewController.hideCamera = YES;
    assetsViewController.delegate = self;
    [self.navigationController pushViewController:assetsViewController animated:YES];
}

- (void)cancelButtonDidPressed {
    PPCameraViewController *cameraViewController = (PPCameraViewController *)self.navigationController;

    if([cameraViewController.cameraDelegate respondsToSelector:@selector(cameraViewControllerDidPressCancel:)]) {
        [cameraViewController.cameraDelegate cameraViewControllerDidPressCancel:cameraViewController];
    }
}

- (void)flashButtonDidPressed {
    [MobClick event:@"23"];
    FastttCameraFlashMode flashMode;

    switch(_camera.cameraFlashMode) {
        case FastttCameraFlashModeOn:
            flashMode = FastttCameraFlashModeOff;
            break;

        case FastttCameraFlashModeOff:
        default:
            flashMode = FastttCameraFlashModeOn;
            break;
    }

    if([_camera isFlashAvailableForCurrentDevice]) {
        _camera.cameraFlashMode = flashMode;

        if(flashMode == FastttCameraFlashModeOn) {
            _flashButton.selected = YES;
        } else {
            _flashButton.selected = NO;
        }
    }
}

- (void)toggleButtonDidPressed {
    [MobClick event:@"24"];
    FastttCameraDevice cameraDevice;

    switch(_camera.cameraDevice) {
        case FastttCameraDeviceFront:
            cameraDevice = FastttCameraDeviceRear;
            break;

        case FastttCameraDeviceRear:
        default:
            cameraDevice = FastttCameraDeviceFront;
            break;
    }

    if([FastttCamera isCameraDeviceAvailable:cameraDevice]) {
        _camera.cameraDevice = cameraDevice;

        if(cameraDevice == FastttCameraDeviceFront) {
            _toggleButton.selected = YES;
        } else {
            _toggleButton.selected = NO;
        }

        if(![_camera isFlashAvailableForCurrentDevice]) {
            _flashButton.selected = NO;
        }
    }
}

- (void)fullButtonDidPressed {
    _fullButton.selected = YES;
    _halfButton.selected = NO;

    [self layoutCameraFrameAnimated:YES];
}

- (void)halfButtonDidPressed {
    [MobClick event:@"25"];
    _fullButton.selected = NO;
    _halfButton.selected = YES;

    [self layoutCameraFrameAnimated:YES];
}

- (void)captureButtonDidPressed {
    [MobClick event:@"27"];
    [_camera takePicture];
}

#pragma mark - IFTTTFastttCameraDelegate

- (void)cameraController:(id<FastttCameraInterface>)cameraController didFinishCapturingImage:(FastttCapturedImage *)capturedImage {
    PPCameraCaptureConfirmViewController *confirmViewController = [[PPCameraCaptureConfirmViewController alloc] init];
    confirmViewController.image = capturedImage.fullImage;
    [self.navigationController pushViewController:confirmViewController animated:YES];
}

- (void)cameraController:(id<FastttCameraInterface>)cameraController didFinishNormalizingCapturedImage:(FastttCapturedImage *)capturedImage {

}

- (BOOL)prefersNavigationBarHidden {
    return YES;
}

#pragma mark - PPAssetsPickerViewControllerDelegate

- (void)assetsPickerViewControllerDidPressCancel:(PPAssetsPickerViewController *)assetsPickerViewController {
    [self.navigationController popToViewController:self animated:YES];
}

- (void)assetsPickerViewControllerDidPressConfirm:(PPAssetsPickerViewController *)assetsPickerViewController {
    if(assetsPickerViewController.selectedAssets.count > 1) {
        [self.navigationController.view toastMessage:@"最多只能选择一张照片"];
        return;
    }
    
    ALAsset *asset = assetsPickerViewController.selectedAssets.firstObject;

    PPCameraViewController *cameraViewController = (PPCameraViewController *)self.navigationController;

    PPCameraCropViewController *cropViewController = [[PPCameraCropViewController alloc] initWithCroppingStyle:TOCropViewCroppingStyleDefault image:asset.image];
    cropViewController.toolbar.cancelIconButton.alpha = 0;
    cropViewController.toolbar.cancelTextButton.alpha = 0;
    cropViewController.delegate = self;
    [cameraViewController pushViewController:cropViewController animated:YES];
}

#pragma mark - TOCropViewControllerDelegate

- (void)cropViewController:(TOCropViewController *)cropViewController didCropToImage:(UIImage *)image withRect:(CGRect)cropRect angle:(NSInteger)angle {
    PPCameraViewController *cameraViewController = (PPCameraViewController *)self.navigationController;

    if([cameraViewController.cameraDelegate respondsToSelector:@selector(cameraViewController:didSelectImages:)]) {
        [cameraViewController.cameraDelegate cameraViewController:cameraViewController didSelectImages:@[image]];
    }
}

- (void)cropViewController:(TOCropViewController *)cropViewController didFinishCancelled:(BOOL)cancelled {
    [self.navigationController popViewControllerAnimated:YES];
}

@end


@implementation FastttCamera (NavigationBar)

- (BOOL)prefersNavigationBarHidden {
    return YES;
}

@end